package fafmessenger_server.control;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Database {

	private static Database ref;
	private final String USERNAME = "root";
	private final String PASSWORD = "matstaco";
	private final String URL = "jdbc:mysql://localhost/fafmessenger";
	private Connection connection = null;
	
	public static Database getRef() {
		if (ref == null) {
			ref = new Database();
		}
		
		return ref;
	}
	
	public boolean connect() {
		boolean returnvalue = false;		
		
		try {
			Class.forName ("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection (URL, USERNAME, PASSWORD);
	        returnvalue = true;
	        
		} catch (Exception e) {
			e.printStackTrace();
		}
				
		return returnvalue;
	}
	
	public ResultSet executeQuery(String query) {
		ResultSet returnvalue = null;
		
		try {
			Statement s = connection.createStatement();
			returnvalue = s.executeQuery(query);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return returnvalue;
	}
	
	public boolean executeUpdate(String query) {
		boolean returnvalue = false;
		
		try {
			Statement s = connection.createStatement();
			int affectedRows = s.executeUpdate(query);
			
			if (affectedRows > 0) {
				returnvalue = true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return returnvalue;
	}
	
	public boolean disconnect() {
		boolean returnvalue = false;
		
		if (connection != null) {
			try {		
				connection.close();
				returnvalue = true;
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return returnvalue;
	}
}
